use crate::db;
use crate::duck::loader::{load_csv, load_excel};
use crate::error::Result;
use crate::models::datasource::file;
use crate::schemas::base::{FilterFunc, FilterItem, FilterValue};
use crate::schemas::duck::DuckData;

pub async fn load_file(ds_id: String) -> Result<DuckData> {
    // 查询数据源对象
    let filters = vec![FilterItem {
        field: "id".into(),
        func: FilterFunc::EQ,
        value: Some(FilterValue::String(ds_id.clone())),
    }];
    let datasource =
        db::read::one::<crate::models::datasource::core::Entity>("project", Some(filters)).await?;

    let mut data: DuckData = DuckData { result: vec![] };

    // 获取详细对象及相关参数
    let filters = vec![FilterItem {
        field: "ds_id".into(),
        func: FilterFunc::EQ,
        value: Some(FilterValue::String(ds_id.clone())),
    }];
    // 不同类型，不同处理
    match datasource.kind.as_str() {
        "csv" => {
            let csv_ds = db::read::one::<file::Entity>("project", Some(filters)).await?;
            data = load_csv(ds_id.clone(), csv_ds.file_path)?;
        }
        "excel" => {
            let excel_ds = db::read::one::<file::Entity>("project", Some(filters)).await?;
            data = load_excel(ds_id.clone(), excel_ds.file_path)?;
        }
        _ => {}
    }
    //
    Ok(data)
}
